package top.yrlby.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import top.yrlby.Config.SendSms;
import top.yrlby.Config.ValidateCodeUtils;
import top.yrlby.common.R;
import top.yrlby.pojo.User;
import top.yrlby.service.UserService;

import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 用户信息 前端控制器
 * </p>
 *
 * @author baiyang
 * @since 2022-09-05
 */
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 发送手机短信验证码
     * @param user
     * @return
     */
    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession session){

        String phone = user.getPhone();//获取前台发送的手机号
        if(StringUtils.isNotBlank(phone)){//判断手机号是否为空
            //生成四位数的验证码
            String code = ValidateCodeUtils.generateValidateCode(4).toString();
            log.info("code={}",code);
//            //调用腾讯云短信服务
//            SendSms.sendMessage(phone,code);
//            //把手机号，验证码存入到session中
//            session.setAttribute(phone,code);
            //需要将生成的验证码保存到Redis,设置过期时间
            redisTemplate.opsForValue().set(phone, code, 5, TimeUnit.MINUTES);
            return R.success("手机验证码短信发送成功"+code);
        }
        return R.error("短信发送失败");
     }

     @PostMapping("/login")
     public R<User> login(@RequestBody Map map , HttpSession session){
        log.info(map.toString());
        //获取前台传递的数据
        String phone = map.get("phone").toString();
        String code = map.get("code").toString();
//        Object attribute = session.getAttribute(phone);

        //从Redis中获取缓存的验证码
        Object attribute = redisTemplate.opsForValue().get(phone);

        //判断前台传递的数据是否为空并且和缓存的验证码进行比较
         if(attribute != null && attribute.equals(code)){
             //创建条件构造器
             LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
             queryWrapper.eq(User::getPhone,phone);//判断手机号是否存在
            //MP生成的单条条件查询
             User user = userService.getOne(queryWrapper);
             if(user==null){//如果不存在则保存数据到SQL
                 user = new User();
                 user.setPhone(phone);
                 user.setStatus(1);
                 userService.save(user);//MP生成的新增
             }
             //保存登录的用户
             session.setAttribute("user",user.getId());
             //登陆成功从Redis中删除缓存的验证码
             redisTemplate.delete(phone);
             return R.success(user);
         }
         return R.error("登陆失败");
     }
}

